import os
from typing import Any
import pandas as pd
from MyLogger import MyLogger
from MyConfig import MyConfig
from MainConsolidator import MainConsolidator
import sys

cur_path = os.path.dirname(os.path.realpath(__file__))
conf = f"{cur_path}\\consolidation.json"
logger = MyLogger(name="debug",log_file="debug.log",outStream=sys.stdout,mode="w")
cfg = MyConfig(conf)
hlist:list = cfg.get("handlers",None)
# hdict:dict = cfg.get("level2 handlers",None)
hdict={}
for item in hlist:
    hdict[item["key"]]=item["module"]
compiled_handlers={}
modules = ["Рулон"]

def handler_cc(rec:pd.Series,consolidator:MainConsolidator)->pd.Series:
    try:
        result:pd.Series={"f1":0}
        module_name=f"__{hdict[rec['Производство2']]}__"
        # logger.info(f"module {module_name}")
        namespace={"consolidator":consolidator , "record":rec, "result":result,"__name__":module_name}
        cc=compiled_handlers[rec["Производство2"]]
        exec(cc,namespace)
        return namespace["result"]
    except Exception as exp: 
        logger.error("handler2 error",exc_info=True)

def get_compiled(key:str)->Any:
    cc=None
    try:
        with open(f"{cur_path}\\handlers2\\{hdict[key]}.py",mode="r",encoding="utf-8") as f:
                code=f.read()
                f.close()
                cc = compile(code,"","exec")
                logger.debug(f"handler '{key}' compiled")
        return cc
    except: raise


if __name__=="__main__":   
    try:
        # module = "Рулон"
        code:str=None
        df = pd.read_excel(f"{cur_path}\\output\\input_data.xlsx",sheet_name="Sheet1")
        cols=df.columns.to_list()+["Продукт УП","error","Время укрупнения"]
        modules_df = df[["Производство2"]].drop_duplicates().to_dict("list")
        for key in modules_df["Производство2"]: compiled_handlers[key]=get_compiled(key)
        # df = df[df["Производство2"]==module]
        logger.info("input data loaded")
        consolidator = MainConsolidator(f"{cur_path}\\debug.log",logStream=sys.stdout)
        consolidator.load_guids("D:\\work\\Укрупнение\\current\\справочники2")
        df = df.apply(lambda row: handler_cc(row,consolidator), axis=1)
        logger.info("handlers applied")
        df[cols].to_excel(f"{cur_path}\\output\\debug_data1.xlsx",index=False)
        logger.info("file saved")
    except:
        logger.error("error",exc_info=True)

    
